package com.neusoft.EYSystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.EYSystem.dao.CaretakerTodayCountDAO;
import com.neusoft.EYSystem.dao.ClientNursingProjectDAO;
import com.neusoft.EYSystem.dao.NursingRecordDAO;
import com.neusoft.EYSystem.dao.UserDAO;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.NursingRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/nursingRecord")
public class NursingRecordController {
    @Autowired
    private NursingRecordService nursingRecordService;
    @Autowired
    private NursingRecordDAO nursingRecordDAO;
    @Autowired
    private CaretakerTodayCountDAO caretakerTodayCountDAO;
    @Autowired
    private ClientNursingProjectDAO clientNursingProjectDAO;
    @Autowired
    private UserDAO userDAO;

    //管理员端 护理管理 按钮进入，根据客户id，表格显示其护理记录
    // 健康管家端 护理管理 日常护理 查询护理记录 根据客户id 表格显示护理记录
    @GetMapping("/pageNursingRecord")
    public PageResponseBean<List<RecordAndProject>> pageNursingRecord(Long cur, Long number, NursingRecord nursingRecord,NursingProject nursingProject) {
        return nursingRecordService.pageNursingRecord(cur, number, nursingRecord, nursingProject);
    }

    @PostMapping("/addNursingRecord")
    public ResponseBean<Integer> addNursingRecord(NursingRecord nursingRecord) {
        ResponseBean<Integer> response = new ResponseBean<>();
        nursingRecord.setIsVisible(true);

        try {
            // 1. 插入护理记录
            int result = nursingRecordDAO.insert(nursingRecord);
            if (result <= 0) {
                response.setStatus(400);
                response.setMsg("护理记录添加失败，可能是数据不完整或重复");
                return response;
            }

            // 2. 根据 client_id 和 project_id 找到对应的启用中的客户护理项目
            Integer clientId = nursingRecord.getClientId();
            Integer projectId = nursingRecord.getProjectId();
            Integer usedQuantity = nursingRecord.getQuantity();

            QueryWrapper<ClientNursingProject> wrapper = new QueryWrapper<>();
            wrapper.eq("client_id", clientId)
                    .eq("project_id", projectId)
                    .eq("status", 1)
                    .last("LIMIT 1"); // 只更新一条

            ClientNursingProject cnp = clientNursingProjectDAO.selectOne(wrapper);
            if (cnp != null) {
                int newQuantity = cnp.getQuantity() - usedQuantity;
                cnp.setQuantity(newQuantity); // 允许为负数
                clientNursingProjectDAO.updateById(cnp);
            }

            response.setStatus(200);
            response.setMsg("护理记录添加成功，已同步扣减客户护理项目数量");
        } catch (Exception e) {
            response.setStatus(500);
            response.setMsg("护理记录添加失败: " + e.getMessage());
        }

        return response;
    }


    @PostMapping("/updateNursingRecord")
    public ResponseBean<String> updateNursingRecord(NursingRecord nursingRecord) {
        return null;
    }

    // 健康管家端 护理管理 日常护理 查询护理记录 表格右侧移除按钮
    @PostMapping("/deleteNursingRecord")
    public ResponseBean<Integer> deleteNursingRecord(NursingRecord nursingRecord) {
        ResponseBean<Integer> response = new ResponseBean<>();

        try {
            // 1. 查询该护理记录的原始数据（包括 clientId、projectId、quantity）
            NursingRecord record = nursingRecordDAO.selectById(nursingRecord.getRecordId());
            if (record == null || !record.getIsVisible()) {
                response.setStatus(400);
                response.setMsg("护理记录不存在或已删除");
                return response;
            }

            // 2. 逻辑删除护理记录（将 is_visible 设置为 false）
            NursingRecord updateRecord = new NursingRecord();
            updateRecord.setRecordId(nursingRecord.getRecordId());
            updateRecord.setIsVisible(false);
            int result = nursingRecordDAO.updateById(updateRecord);

            // 3. 将 quantity 加回客户护理项目表
            Integer clientId = record.getClientId();
            Integer projectId = record.getProjectId();
            Integer restoreQuantity = record.getQuantity();

            QueryWrapper<ClientNursingProject> wrapper = new QueryWrapper<>();
            wrapper.eq("client_id", clientId)
                    .eq("project_id", projectId)
                    .eq("status", 1)
                    .last("LIMIT 1");

            ClientNursingProject cnp = clientNursingProjectDAO.selectOne(wrapper);
            if (cnp != null) {
                int newQuantity = cnp.getQuantity() + restoreQuantity;
                cnp.setQuantity(newQuantity);
                clientNursingProjectDAO.updateById(cnp);
            }

            response.setStatus(200);
            response.setMsg("护理记录删除成功，已恢复客户护理项目次数");
            response.setData(result);

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            response.setMsg("逻辑删除护理记录失败: " + e.getMessage());
        }

        return response;
    }


    //返回今天所有做过护理记录的职工id和职工项目和这个职工护理次数
    @GetMapping("/todayCaretakerCount")
    public ResponseBean<List<CaretakerTodayCount>> getCaretakerTodayCount() {
        ResponseBean<List<CaretakerTodayCount>> response = new ResponseBean<>();
        try {
            List<CaretakerTodayCount> result = caretakerTodayCountDAO.getCaretakerTodayCount();
            response.setStatus(200);
            response.setMsg("查询成功");
            response.setData(result);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            response.setMsg("查询失败：" + e.getMessage());
        }
        return response;
    }

    @GetMapping("/todayCaretakerCountById")
    public ResponseBean<Integer> getCaretakerTodayCountById(@RequestParam Long userId) {
        ResponseBean<Integer> response = new ResponseBean<>();
        try {
            // 1. 根据 userId 查询用户名
            User user = userDAO.selectById(userId);
            if (user == null) {
                response.setStatus(404);
                response.setMsg("未找到该护工用户");
                return response;
            }
            String username = user.getUsername();

            // 2. 获取所有护工今日护理次数统计
            List<CaretakerTodayCount> result = caretakerTodayCountDAO.getCaretakerTodayCount();

            // 3. 匹配 username 获取对应 count
            Integer count = result.stream()
                    .filter(c -> c.getName().equals(username))
                    .map(CaretakerTodayCount::getCount)
                    .findFirst()
                    .orElse(0); // 如果没查到则默认返回 0

            // 4. 返回结果
            response.setStatus(200);
            response.setMsg("查询成功");
            response.setData(count);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            response.setMsg("查询失败：" + e.getMessage());
        }
        return response;
    }


}
